use serde::{Deserialize, Serialize};
use std::collections::VecDeque;
use std::sync::Mutex;
use rand::Rng;
use std::sync::{LazyLock};

use askama::Template;
use axum::{

    response::{Html, IntoResponse},

};

use axum_messages::{Message, Messages};
use axum::extract::Query;
use crate::users::AuthSession;


use crate::logdb::LogEntry;
use crate::logdb::read_logs;
use crate::logdb::log_init_db;

#[derive(Template)]
#[template(path = "log.html")]
pub struct LogTemplate<'a> {
    messages: Vec<Message>,
    username: &'a str,
    logs: Vec<LogEntry>,             // 日志条目列表
    current_page: i32,               // 当前页码
    total_pages: i32,                // 总页数
    total_logs: i32,                 // 总日志数
}

#[derive(Template)]
#[template(path = "auditor.html")]
pub struct AuditorLogTemplate<'a> {
    messages: Vec<Message>,
    username: &'a str,
    logs: Vec<LogEntry>,             // 日志条目列表
    current_page: i32,               // 当前页码
    total_pages: i32,                // 总页数
    total_logs: i32,                 // 总日志数
}

// 使用 LazyLock 延迟初始化（运行时执行）
static LOG_STORAGE: LazyLock<Mutex<VecDeque<LogEntry>>> = LazyLock::new(|| {
    Mutex::new(VecDeque::with_capacity(1000)) // 或 VecDeque::default()
});

// 模拟生成测试日志
fn generate_test_logs() {
    let mut rng = rand::thread_rng();
    let actions = ["登录", "注销", "修改配置", "删除文件"];
    let levels = ["info", "warning", "error"];

    for k in 0..100 {
        let entry = LogEntry {
            id: k,
            timestamp: chrono::offset::Local::now().format("%Y-%m-%d %H:%M:%S").to_string(),
            level: levels[rng.gen_range(0..levels.len())].to_string(),
            username: format!("user_{}", rng.gen_range(1..100)),
            message: actions[rng.gen_range(0..actions.len())].to_string(),
            ip: "".to_string(),
            detail: format!("操作详情: 第 {} 条日志", rng.gen_range(1..1000)),
        };
        LOG_STORAGE.lock().unwrap().push_front(entry);
    }
}

// 分页查询参数
#[derive(Deserialize)]
pub struct PaginationQuery {
    page: Option<i32>,
    limit: Option<i32>,
    search: Option<String>,
    level: Option<String>,
}

// 获取日志列表接口
async fn get_logs(query: PaginationQuery) -> LogResponse {
    // 解锁后自动释放锁，无需手动管理 MutexGuard
    let pool = log_init_db().await.expect("Failed to initialize database");
    let mut logs = read_logs(&pool).await.expect("failed to read all logs from db ");

    // 搜索过滤
    if let Some(search) = query.search {
        logs.retain(|entry| entry.message.contains(&search) || entry.username.contains(&search));
    }

    // 级别过滤
    if let Some(level) = query.level {
        logs.retain(|entry| entry.level == level);
    }

    // 按时间倒序：最新在前
    logs.sort_by(|a, b| b.timestamp.cmp(&a.timestamp));
    
    // 分页处理
    let page = query.page.unwrap_or(1);
    let limit = query.limit.unwrap_or(10);
    let start = (page - 1) * limit;
    let total = logs.len();
    let total_pages = (total + limit as usize - 1) / limit as usize;

    let paginated_logs = logs.into_iter()
        .skip(start as usize)
        .take(limit as usize)
        .collect();

    LogResponse {
        logs: paginated_logs,
        current_page: page,
        total_pages: total_pages as i32,
        total: total.try_into().unwrap(),
    }
}

// 响应结构体
#[derive(Serialize)]
pub struct LogResponse {
    logs: Vec<LogEntry>,
    current_page: i32,
    total_pages: i32,
    total: i32,
}



pub mod get {
    use super::*;
    pub async fn auditor_log_lookup(
        auth_session: AuthSession, 
        messages: Messages, 
        Query(query): Query<PaginationQuery>,
    ) -> impl IntoResponse {
        generate_test_logs();

        
       
        // 获取日志数据（复用原有 get_logs 逻辑）
        let logs_response = get_logs(query).await;
        
        match auth_session.user {
            Some(user) => {
                // 构建包含日志数据的模板
                let template = AuditorLogTemplate {
                    messages: messages.into_iter().collect(),
                    username: &user.username,
                    logs: logs_response.logs,
                    current_page: logs_response.current_page,
                    total_pages: logs_response.total_pages,
                    total_logs: logs_response.total,
                };
                
                Html(template.render().unwrap()).into_response()
            }
            None => {
                // 未登录用户也可以查看日志（用户名显示为 "none"）
                let template = AuditorLogTemplate {
                    messages: messages.into_iter().collect(),
                    username: "none",
                    logs: logs_response.logs,
                    current_page: logs_response.current_page,
                    total_pages: logs_response.total_pages,
                    total_logs: logs_response.total,
                };
                
                Html(template.render().unwrap()).into_response()
            }
        }
    }
    pub async fn log_lookup(
        messages: Messages, 
        Query(query): Query<PaginationQuery>,
    ) -> impl IntoResponse {
        generate_test_logs();

        return log_lookup_inner(messages, query).await;
    }

    pub async fn log_lookup_inner(
        messages: Messages, 
        query: PaginationQuery,
    ) -> impl IntoResponse {
        generate_test_logs();
        
       
        // 获取日志数据（复用原有 get_logs 逻辑）
        let logs_response = get_logs(query).await;
        
        // 未登录用户也可以查看日志（用户名显示为 "none"）
        let template = LogTemplate {
            messages: messages.into_iter().collect(),
            username: "none",
            logs: logs_response.logs,
            current_page: logs_response.current_page,
            total_pages: logs_response.total_pages,
            total_logs: logs_response.total,
        };
        
        Html(template.render().unwrap()).into_response()
    }    
}
